import i18n from '@/i18n'
import Vue from 'vue'

import regExp from '@/service/regExp'

let vueI18n = new Vue({
  i18n
})

const cu = {
  state: {
    checkRules: {},
    centerCuCheckRules: {
      device: [
        // 请输入业务终端编号
        { required: true, message: vueI18n.$t('message.validate.devices.cu.device'), trigger: 'blur' },
        // 请输入正整数
        { pattern: regExp.positiveInteger, message: vueI18n.$t('message.validate.common.integer'), trigger: 'blur' }
      ],
      number: [
        // 请输入业务终端号码
        { required: true, message: vueI18n.$t('message.validate.devices.cu.number'), trigger: 'blur' },
        // 请输入正整数
        { pattern: regExp.positiveInteger, message: vueI18n.$t('message.validate.common.integer'), trigger: 'blur' }
      ],
      address: [
        // 请输入业务终端地址
        { required: true, pattern: regExp.ip, message: vueI18n.$t('message.validate.devices.cu.address'), trigger: 'blur' }
      ],
      kind: [
        // 请选择业务终端类型
        { required: true, message: vueI18n.$t('message.validate.devices.cu.kind'), trigger: 'blur' }
      ],
      antenna: [
        // 请选择业务终端天线
        { required: true, message: vueI18n.$t('message.validate.devices.cu.antenna'), trigger: 'blur' }
      ],
      unit_type: [
        // 请选择类型
        { required: true, message: vueI18n.$t('message.validate.devices.cu.unit_type'), trigger: 'change' }
      ]
    },

    // 首页表格中的culist
    collectionCuList: [],
    // 普通分页的culist
    cuList: [],
    cuCount: 0,

    cuLogOutNotify: null
  },
  mutations: {
    setCuList (state, data) {
      let collectionCuIdList = localStorage.getItem('cuIdList')
        ? JSON.parse(localStorage.getItem('cuIdList')) : []
      state.cuCount = data.count
      state.cuList = [
        ...data.results.map(item => {
          return {
            ...item,
            collected: !!collectionCuIdList.find(cuId => cuId === item.id),
            init_tdm_frequency: '',
            power_adjust: ''
          }
        })
      ]
    },
    setCuListCollected (state, data) {
      state.cuList[data.index].collected = data.collected
    },
    setCollectionCuList (state, data) {
      state.collectionCuList = [
        ...data.map(item => {
          return {
            ...item,
            init_tdm_frequency: '',
            power_adjust: ''
          }
        })
      ]
    },
    // 取消收藏时，删除该终端
    deleteCuCollected (state, data) {
      for (let key in state.collectionCuList) {
        if (state.collectionCuList[key].id === data.id) {
          state.collectionCuList.splice(key, 1)
          break
        }
      }
    },
    setCuState (state, data) {
      // 远端站culist
      if (state.cuList.find(item => item.device === data.device)) {
        state.cuList.find(item => item.device === data.device).state = data.state
      }
      // collection  culist
      if (state.collectionCuList.find(item => item.device === data.device)) {
        state.collectionCuList.find(item => item.device === data.device).state = data.state
      }
    },
    // 12-18临时
    cuLogOutNotify (state, data) {
      state.cuLogOutNotify = data
    },
    setCuConfig (state, data) {
      if (state.centerCuList.find(item => item.id === data.id)) {
        state.centerCuList.find(item => item.id === data.id).init_tdm_frequency = data.init_tdm_frequency
        state.centerCuList.find(item => item.id === data.id).power_adjust = data.power_adjust
      }
    },
    setCuSnr (state, data) {
      if (state.cuList.find(item => item.device === data.cu_device)) {
        state.cuList.find(item => item.device === data.cu_device).snr1 = data.snr1
        state.cuList.find(item => item.device === data.cu_device).snr2 = data.snr2
      }
    }
  },
  actions: {
    async getCuList (context, payload = {
      page: 1,
      pageSize: 10,
      ordering: 'device'
    }) {
      let response = await context.dispatch(`axios`, {
        method: 'get',
        params: {
          station__dept__center: false,

          ordering: payload.ordering || 'device',

          page: payload.page || 1,
          page_size: payload.pageSize || 10,

          search: payload.info
        },
        url: '/api/abs/devices/cus/'
      })
      context.commit('setCuList', response.data)
    },
    // async getCuSnrById (context, payload) {
    //   let response = await context.dispatch(`axios`, {
    //     method: 'get',
    //     url: `/api/abs/ncp/cu_snr/${payload.id}/`
    //   })
    //   context.commit('setCuSnrByIndex', {
    //     id: payload.id,
    //     snr1: response.data.snr1,
    //     snr2: response.data.snr2
    //   })
    // },
    async getCollectionCuList (context) {
      let cuIdList = []
      try {
        cuIdList = localStorage.getItem('cuIdList')
          ? JSON.parse(localStorage.getItem('cuIdList')) : []
        cuIdList = cuIdList.join(',')
      } catch (e) {
        console.log('localStorage “cuIdList” parse error,clear it to prevent mistakes')
        localStorage.removeItem('cuIdList')
        return
      }
      // 如果列表为空，直接返回
      if (cuIdList.length === 0) return
      let response = await context.dispatch(`axios`, {
        method: 'get',
        url: '/api/abs/devices/cus/',
        params: {
          id_list: cuIdList
        }
      })
      // console.log('collection', response.data)
      context.commit('setCollectionCuList', response.data.results)
    },
    async getCuConfig (context, payload) {
      let response = await context.dispatch(`axios`, {
        method: 'get',
        url: `/api/abs/ncp/cu_config/${payload}/`
      })
      context.commit('setCuConfig', {
        id: payload,
        init_tdm_frequency: response.data.basic.initTDMFrequency[0],
        power_adjust: response.data.power.powerAdjust
      })
      // console.log({
      //   id: payload,
      //   init_tdm_frequency: response.data.basic.initTDMFrequency[0],
      //   power_adjust: response.data.power.powerAdjust
      // })
    }
  },
  getters: {
    getCuOfRemote: (state, getters, rootState) => {
      return [...state.cuList.map(item => {
        let sendFreq = ''
        let receiveFreq = ''
        let caller = rootState.sessions.usingTrafficChannel.find(usingItem => usingItem.caller_cu_id === item.id)
        let called = rootState.sessions.usingTrafficChannel.find(usingItem => usingItem.called_cu_id === item.id)
        if (caller) {
          sendFreq = (caller.caller_up_freq_begin + caller.caller_up_freq_end) / 2
          receiveFreq = (caller.caller_down_freq_begin + caller.caller_down_freq_end) / 2
        }
        if (called) {
          sendFreq = (called.called_up_freq_begin + called.called_up_freq_end) / 2
          receiveFreq = (called.called_down_freq_begin + called.called_down_freq_end) / 2
        }
        return {
          ...item,
          sendFreq,
          receiveFreq
        }
      })]
    },
    getCuOfCollection: (state, getters, rootState) => {
      return [...state.collectionCuList.map(item => {
        let sendFreq = ''
        let receiveFreq = ''
        let caller = rootState.sessions.usingTrafficChannel.find(usingItem => usingItem.caller_cu === item.device)
        let called = rootState.sessions.usingTrafficChannel.find(usingItem => usingItem.called_cu === item.device)
        if (caller) {
          sendFreq = (caller.caller_up_freq_begin + caller.caller_up_freq_end) / 2
          receiveFreq = (caller.caller_down_freq_begin + caller.caller_down_freq_end) / 2
        }
        if (called) {
          sendFreq = (called.called_up_freq_begin + called.called_up_freq_end) / 2
          receiveFreq = (called.called_down_freq_begin + called.called_down_freq_end) / 2
        }
        return {
          ...item,
          sendFreq,
          receiveFreq
        }
      })]
    }
  }
}
export default cu
